
import random
import re

from flask import abort, jsonify
from flask import current_app
from flask import make_response
from flask import request
from flask import session

from info import constants, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha

from info import redis_store
from info.utils.response_code import RET
from . import passport_blu
from datetime import datetime
@passport_blu.route('/logout')
def logout():
    session.pop('user_id',None)
    session.pop('user_mobile',None)
    session.pop('nick_name',None)
    return jsonify(errno=RET.OK,errmsg='退出成功')
@passport_blu.route('/login',methods=['POST','GET'])
def login():
    mobile=request.json.get('mobile',None)
    password=request.json.get('password',None)
    if not all([mobile,password]):
        return jsonify(errno=RET.NODATA,errmsg='参数错误')
    try:
        user=User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')
    if not user:
        return jsonify(errno=RET.DATAERR,errmsg='该用户没有注册')
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR, errmsg='用户名或密码错误')
    session["user_id"] = user.id
    session["user_mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    user.last_login = datetime.now()
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据保存失败')
    return jsonify(errno=RET.OK,errmsg='登录成功')


@passport_blu.route('/register',methods=['POST','GET'])
def register():
    print("ok--------------------------------")
    mobile=request.json.get('mobile',None)
    smsCode=request.json.get('smscode',None)
    password=request.json.get('password',None)
    try:
        user=User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据查询失败')
    if user:
        return jsonify(errno=RET.DATAERR,errmsg='该用户已经注册')
    if not all([mobile,smsCode,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        sms_code=redis_store.get(mobile)
        if not sms_code:
            return jsonify(errno=RET.THIRDERR,errmsg='短信验证码已过期')
    except Exception as e:
        current_app.logger.error(e)
        abort(500)
    if smsCode!=sms_code:
        return jsonify(errno=RET.DATAERR,errmsg='验证码输入错误')
    user=User()
    user.mobile=mobile
    user.nick_name=mobile

    user.last_login=datetime.now()
    user.password=password
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='数据保存失败')
    session["user_id"]=user.id
    session["user_mobile"]=user.mobile
    session["nick_name"]=user.nick_name
    return jsonify(errno=RET.OK,errmsg='注册成功')


@passport_blu.route('/sms_code',methods=['POST'])
def send_sms_code():
    mobile=request.json.get('mobile',None)
    image_code=request.json.get('image_code',None)
    image_code_id=request.json.get('image_code_id',None)
    if not mobile:
        return jsonify(errno=RET.NODATA,errmsg='手机号不能为空')
    if not re.match(r'1[35678]\d{9}',mobile):
        return jsonify(errno=RET.DATAERR, errmsg='手机号格式有误')
    if not image_code:
        return jsonify(errno=RET.NODATA, errmsg='验证码不能为空')
    try:
        imageCode=redis_store.get("imageCodeId"+image_code_id)
        if not imageCode:
            return jsonify(errno=RET.NODATA,errmsg='图片验证码已经过期')
    except Exception as e:
        current_app.logger.error(e)
        abort(500)
    if imageCode.upper()==image_code.upper():
        # 注意： 测试的短信模板编号为1
        sms_code_str="%06d"%random.randint(0, 999999)
        print(sms_code_str)
        # result=CCP().send_template_sms('18986629768', [sms_code_str, 5], 1)
        # if result!=0:
        #     return jsonify(errno=RET.THIRDERR,errmsg="验证码发送失败")
        try:
            redis_store.set(mobile,sms_code_str,constants.SMS_CODE_REDIS_EXPIRES)
        except Exception as e:
            current_app.logger.error(e)
            abort(500)
        return jsonify(errno=RET.OK,errmsg='验证码发送成功')
    # print(request.json.get('mobile'))


@passport_blu.route('/image_code')
def get_image_code():
    image_code_id=request.args.get("imageCodeId",None)
    if not image_code_id:
        return  abort(403)
    name,text,image=captcha.generate_captcha()
    # print(name,text,image)
    print(text)
    try:
        redis_store.set("imageCodeId"+image_code_id,text,constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        abort(500)
    response=make_response(image)
    response.headers["Content-Type"]="image/jpg"
    return response

